package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import jdk.nashorn.internal.ir.SplitReturn;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        // 从redis中查询店铺类型
        String key = "cache:shopType:" + UUID.randomUUID().toString(true);
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        List<ShopType> typeList = null;
        // 判断缓存是否命中
        if (StrUtil.isNotBlank(shopTypeJson)) {
            // 命中直接返回
            typeList = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(typeList);
        }
        // 缓存未命中查询数据库
        typeList = this.list(new LambdaQueryWrapper<ShopType>().orderByAsc(ShopType::getSort));
        // 判断数据库中是否存在该数据
        if (Objects.isNull(typeList)) {
            return Result.fail("店铺类型不存在");
        }
        // 数据存在，写入redis并返回
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(typeList), 30L, TimeUnit.MINUTES);
        return Result.ok(typeList);
    }
}
